<template>
    <div class="techaer-detail">
        <el-card shadow="never" class="!border-none">
            <el-page-header :content="id ? '编辑区域' : '新增区域'" @back="$router.back()" />
        </el-card>

        <el-form
            ref="formRef"
            :model="formData"
            label-width="120px"
            class="demo-formData"
            :rules="formRules"
        >
            <el-card shadow="never" class="!border-none mt-4">
                <el-form-item label="省市:" prop="province">
                    <el-cascader
                        ref="cascaderRef"
                        v-model="formData.city_id"
                        :options="optionsData.arealists"
                        :show-all-levels="false"
                        :props="{
                            children: 'sub',
                            label: 'name',
                            value: 'id',

                            emitPath: false
                        }"
                        @change="getSelectValue"
                    />
                </el-form-item>
                <el-form-item label="区域:" prop="area">
                    <div>
                        <popup
                            width="800px"
                            class="-mt-4 inline"
                            title="添加区域"
                            @open="handleopen"
                        >
                            <template #trigger>
                                <el-button type="primary">添加区域</el-button>
                            </template>
                            <div>
                                <el-checkbox
                                    v-model="checkAll"
                                    :indeterminate="isIndeterminate"
                                    @change="handleCheckAllChange"
                                    >全部</el-checkbox
                                >
                                <el-checkbox-group
                                    v-model="formData.area"
                                    @change="handleCheckedCitiesChange"
                                >
                                    <el-checkbox
                                        v-for="city in cityLists"
                                        :key="city.id"
                                        :label="city.id"
                                        >{{ city.name }}</el-checkbox
                                    >
                                </el-checkbox-group>
                            </div>
                        </popup>
                    </div>
                </el-form-item>
            </el-card>
        </el-form>

        <footer-btns>
            <el-button type="primary" @click="handleAdd">保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang="ts" setup>
import { areaRegion, areaDistrict, areaAdd, areaLists, areaDetail, areaEdit } from '@/api/teamhead'
import FooterBtns from '@/components/footer-btns/index.vue'
import { useDictOptions } from '@/hooks/useDictOptions'
import type { ElForm } from 'element-plus'
import feedback from '@/utils/feedback'

type FormInstance = InstanceType<typeof ElForm>

const route = useRoute()
const router = useRouter()
const id: any = route.query.id
const formData = ref<any>({
    id: '',
    city_id: '',
    province_id: '',
    area: []
})
const checkAll = ref(false)
const isIndeterminate = ref(true)
const cityLists = ref<any[]>([])
const cityid = ref<any[]>([])
//全选
const handleCheckAllChange = (val: any) => {
    formData.value.area = val ? cityid.value : []
    isIndeterminate.value = false
}

const handleCheckedCitiesChange = (value: any[]) => {
    const checkedCount = value.length
    checkAll.value = checkedCount === cityLists.value.length
    isIndeterminate.value = checkedCount > 0 && checkedCount < cityLists.value.length
}
//选择框数据
const { optionsData } = useDictOptions<{
    arealists: any[]
}>({
    arealists: {
        api: areaRegion
    }
})

//添加区域popup
const handleopen = async () => {
    const res = await areaDistrict({ city_id: formData.value.city_id })
    cityLists.value = res
    cityid.value = cityLists.value.map((item) => {
        return item.id
    })
    const data = await areaLists({ region: formData.value.city_id })
    if (!data.lists[0]) return
    formData.value.area = data.lists[0].area.map(Number)
}
//保存
const formRef = shallowRef<FormInstance>()
const handleAdd = async () => {
    try {
        // await formRef.value?.validate()
        if (route.query.id) {
            await areaEdit(formData.value)
        } else {
            await areaAdd(formData.value)
        }
        feedback.msgSuccess('操作成功')
        router.back()
    } catch (error: any) {
        console.log(error)
    }
}

const cascaderRef = ref()
const getSelectValue = () => {
    const node = cascaderRef.value.getCheckedNodes()
    formData.value.province_id = node[0].data.parent_id
    formData.value.city_id = node[0].data.id
}
const getDetails = async () => {
    if (!route.query.id) return
    const data = await areaDetail({
        id: route.query.id
    })
    formData.value = data
}
getDetails()
//校验
const formRules = {
    province: [
        {
            required: true,
            message: '请选择省市',
            trigger: ['blur']
        }
    ],
    area: [
        {
            required: true,
            message: '请选择区域',
            trigger: ['blur']
        }
    ]
}
</script>
